<template>
  <div>
    <a-modal title="创建交货单" :visible="visible" @before-open="open" @cancel="handleCancel" :align-center="false" title-align="start" width="1200px" :mask-closable="false">
      <div>
        <a-form auto-label-width ref="formRef" size="medium" :model="form">
          <a-row style="padding: 0 20px">
            <a-col :span="8">
              <a-form-item field="isAcceptOrder" label="是否需要扣减库存：">
                <a-select placeholder="请选择" v-model="form.deliveryDeduction">
                  <a-option label="需要扣减库存" :value="1"></a-option>
                  <a-option label="不需要" :value="2"></a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="16">
              <a-form-item field="isAcceptOrder" label="交货仓库：">
                <a-select placeholder="请选择" @change="getWarehouseStock" v-model="form.deliveryWarehouseCode" style="width: 160px" allow-clear allow-search>
                  <a-option v-for="item of houseList" :label="item.warehouseName" :value="item.warehouseCode"></a-option>
                </a-select>
                <span class="text-desc">如果需要扣减库存则必须选择交货仓且库存足够</span>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item field="isAcceptOrder" label="物流方式：">
                <a-select placeholder="请选择" v-model="form.logisticType">
                  <a-option label="线下配送" value="1"></a-option>
                  <a-option label="快递" value="2"></a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="14">
              <a-form-item field="isAcceptOrder" label="物流跟踪号：">
                <a-input placeholder="物流商" v-model="form.logisticName" />
                <a-input placeholder="物流跟踪号" v-model="form.logisticsTrackNumber" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="title-bar">交货明细</div>

      <div class="table">
        <a-table class="table-two-line" ref="tableListref" style="width: 1160px" :summary="summary" :span-method="spanMethodAll" row-key="id" :expandable="expandable" :default-expand-all-rows="true" :bordered="false" :columns="tableColumns" :data="tableList" size="mini" :pagination="false" :scroll="{ y: '300px' }">
          <template #columns>
            <a-table-column v-for="(item, index) of tableColumns" :fixed="item.fixed" :key="index" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
              <template v-if="item.dataIndex == 'img'" #cell="{ record }">
                <!-- <div class="flex-c-sb" style="display: flex; align-items: center"> -->
                <div style="display: flex; align-items: center">
                  <div class="order-w flex">
                    <p>
                      <span class="label">采购单号：</span>
                      <span>{{ record.billNo }}</span>
                    </p>
                    <p style="margin: 0 20px">
                      <span class="label">经销商：</span>
                      <span>{{ record.companyName }}</span>
                    </p>
                    <p>
                      <span class="label">提交日期：</span>
                      <span>{{ $setTime(record.gmtAudit) }}</span>
                    </p>
                  </div>
                </div>
              </template>
            </a-table-column>
          </template>
          <template #expand-row="option">
            <a-table class="table-singe-line" row-class="child-row" v-model:selected-keys="ids" :row-selection="rowSelection" :show-header="false" row-key="id" :bordered="false" :columns="tableColumns" :data="option.record.billItems" size="mini" :pagination="false">
              <template #columns>
                <a-table-column v-for="(item, index) of tableColumns" :key="index" :fixed="item.fixed" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
                  <template v-if="item.dataIndex == 'img'" #cell="option">
                    <ImgPopover :src="option.record.productImg">
                      <template #con>
                        <a-image width="40" height="40" fit="contain" :src="option.record.productImg" />
                      </template>
                    </ImgPopover>
                  </template>
                  <template v-else-if="item.dataIndex == 'productName'" #cell="option">
                    <TextLimit position="top">{{ option.record.productName }}</TextLimit>
                  </template>

                  <template v-else-if="item.dataIndex == 'productSpecs'" #cell="option">
                    <TextLimit position="top">{{ getSpecName(option.record) }}</TextLimit>
                  </template>

                  <template v-else-if="item.dataIndex == 'gmtPlanDelivery'" #cell="option">
                    <div>{{ $setTime(option.record.gmtPlanDelivery, 'YYYY/MM/DD') }}</div>
                    <div v-if="option.record.gmtPlanDelivery">
                      <div style="color: red" v-if="!toCheckDay(option.record.gmtPlanDelivery).type">超时{{ toCheckDay(option.record.gmtPlanDelivery).day }}天</div>
                      <div class="highlight" v-else>剩余{{ toCheckDay(option.record.gmtPlanDelivery).day }}天</div>
                    </div>
                  </template>
                  <template v-else-if="item.dataIndex == 'deliveryStayAmt'" #cell="{ record }">
                    <span>{{ record.deliveryStayAmt }}</span>
                  </template>
                  <template v-else-if="item.dataIndex == '本次交货'" #cell="{ record, rowIndex }">
                    <a-space>
                      <a-input-number v-model="record.deliveryAmt" hide-button style="width: 90px" :min="0" :max="record.deliveryStayAmt" placeholder="" />
                      <a-button size="small" class="gray-outline" @click="setGlobal(option.record, record, 'deliveryAmt', 'deliveryStayAmt', rowIndex)">
                        <template #icon>
                          <icon-double-down />
                        </template>
                      </a-button>
                    </a-space>
                  </template>
                  <template v-else-if="item.dataIndex == '交货仓可用库存'" #cell="{ record }">{{ record.warehouseStock }} </template>
                  <template v-else-if="item.dataIndex == 'rate'" #cell="{ record }"> {{ record.rate }}% </template>
                  <template v-else-if="item.dataIndex == 'price'" #cell="{ record }">
                    <div class="highlight">{{ record.priceType ? '含税' : '不含税' }}</div>
                    <div>￥{{ record.price }}</div>
                  </template>
                  <template v-else-if="item.dataIndex == '本次交货金额'" #cell="{ record }">
                    <div class="highlight">{{ record.priceType ? '含税' : '不含税' }}</div>
                    <div>￥{{ (record.deliveryAmt || 0) * (record.price || 0) }}</div>
                  </template>
                  <!-- <template v-else-if="item.dataIndex == '库存单价'" #cell="{ record, rowIndex }">
                    <a-space>
                      <a-input-number v-model="record.deliveryInventoryPrice" hide-button style="width: 90px" :min="0" placeholder="" />
                      <a-button size="small" class="gray-outline" @click="setGlobal(option.record, record, 'deliveryInventoryPrice', false, rowIndex)">
                        <template #icon>
                          <icon-double-down />
                        </template>
                      </a-button>
                    </a-space>
                  </template>
                  <template v-else-if="item.dataIndex == '库存成本'" #cell="{ record }">{{ (record.deliveryInventoryPrice || 0) * (record.deliveryAmt || 0) }} </template> -->

                  <template v-else-if="item.dataIndex == '操作'" #cell="{ record, rowIndex }">
                    <a-button type="text" @click="record.delete = true">移除</a-button>
                  </template>
                </a-table-column>
              </template>
            </a-table>
          </template>
          <template #summary-cell="{ column, record, rowIndex }" v-if="visible">
            <div>{{ record[column.dataIndex] }}</div>
          </template>
        </a-table>
      </div>

      <template #footer>
        <a-button class="gray-outline" @click="handleCancel">取消</a-button>
        <a-button type="primary" :loading="loading" class="ml10" @click="handleOk">确认</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs, computed } from 'vue'
  import { findWarehouseListByParam } from '@/api/warehouse'
  import { findInventoryBatch } from '@/api/order'
  import { supplierCreateDeliveryOrder } from '@/api/supplier'
  import { Message } from '@arco-design/web-vue'
  import _ from 'lodash-es'
  export default defineComponent({
    props: ['type', 'list'],
    setup(props: any, { emit }) {
      let visible = ref(false)
      const formRef = ref()
      const data: any = reactive({
        rules: [],
        form: {},
        houseList: [],
        tableColumns: [
          {
            title: '图片',
            dataIndex: 'img',
            width: 60,
          },
          {
            title: '产品名称',
            dataIndex: 'productName',
            width: 120,
          },
          {
            title: '供应商SKU',
            dataIndex: 'ssku',
            width: 140,
          },
          {
            title: '经销商SKU',
            dataIndex: 'sku',
            width: 140,
          },
          {
            title: '规格',
            dataIndex: 'productSpecs',
            width: 140,
          },
          {
            title: '期望交期',
            dataIndex: 'gmtPlanDelivery',
            width: 140,
          },
          {
            title: '采购数',
            dataIndex: 'purchaseAmt',
            width: 70,
          },
          {
            title: '截单数',
            dataIndex: 'cutoffAmt',
            width: 70,
          },
          // {
          //   title: '交货数',
          //   dataIndex: 'deliveryAmt',
          //   width: 70,
          // },
          {
            title: '已交货数',
            dataIndex: 'deliveryRealAmt',
            width: 100,
          },
          {
            title: '未交货',
            dataIndex: 'deliveryStayAmt',
            width: 70,
          },
          {
            title: '*本次交货',
            dataIndex: '本次交货',
            width: 140,
          },
          {
            title: '交货仓可用库存',
            dataIndex: '交货仓可用库存',
            width: 140,
          },
          {
            title: '税率',
            dataIndex: 'rate',
            width: 60,
          },
          {
            title: '单价',
            dataIndex: 'price',
            width: 80,
          },
          {
            title: '本次交货金额',
            dataIndex: '本次交货金额',
            width: 100,
          },
          // {
          //   title: '库存成本',
          //   dataIndex: '库存成本',
          //   width: 80,
          // },
          {
            title: '操作',
            dataIndex: '操作',
            width: 80,
          },
        ],
        expandable: {
          title: '',
          defaultExpandAllRows: true,
          expandedRowKeys: [],
          width: 10,
        },
        tableList: [],
        itemList: [],
        amtAvailableResList: [],
      })

      const open = () => {
        getWareHouseList()
        data.itemList = []
        data.tableList = _.cloneDeep(props.list)

        data.tableList.forEach((e: any) => {
          e.billItems.map((el: any) => {
            el.deliveryAmt = 0
            return el
          })
          return e
        })
        data.expandable.expandedRowKeys = data.tableList.map((el: any) => el.id)
        data.tableList.forEach((e: any) => {
          let arr = e.billItems.map((el: any) => {
            el.billId == e.billNo
            return el
          })
          data.itemList = [...data.itemList, ...arr]
        })
      }
      const handleOk = async () => {
        let params = {
          ...data.form,
          deliveryItems: [],
        }
        params.deliveryDeduction == 1 ? (params.deliveryDeduction = true) : (params.deliveryDeduction = false)
        data.itemList.forEach((e: any) => {
          let obj = {
            billId: e.billId,
            deliveryAmt: e.deliveryAmt,
            id: e.id,
            deliveryInventoryPrice: e.deliveryInventoryPrice,
            deliveryRealAmt: e.deliveryRealAmt,
          }
          params.deliveryItems.push(obj)
        })

        data.loading = true

        await supplierCreateDeliveryOrder(params)
        data.loading = false
        Message.success('创建交货单成功')
        handleCancel()
        emit('save')
      }
      const handleCancel = () => {
        formRef.value.resetFields()
        formRef.value.clearValidate()
        data.form = {}
        data.tableList = []
        visible.value = false
      }

      const getWareHouseList = async () => {
        const res = await findWarehouseListByParam()
        let arr = res?.data
        data.houseList = arr
      }

      // 合并单元格
      const spanMethodAll = (option: any) => {
        let { column } = option
        if (column.dataIndex === 'img') {
          return { rowspan: 1, colspan: 16 }
        }
      }

      const summary = () => {
        let purchaseAmt = 0
        let cutoffAmt = 0
        let deliveryRealAmt = 0
        let deliveryStayAmt = 0
        let 本次交货 = 0
        let 交货仓可用库存 = 0
        let 库存成本 = 0

        data.itemList.forEach((e: any) => {
          purchaseAmt += e.purchaseAmt || 0
          cutoffAmt += e.cutoffAmt || 0
          deliveryRealAmt += e.deliveryRealAmt || 0
          deliveryStayAmt += e.deliveryStayAmt || 0
          本次交货 += e.deliveryAmt || 0
          交货仓可用库存 += e.warehouseStock || 0
          库存成本 += (e.deliveryInventoryPrice || 0) * (e.deliveryAmt || 0)
        })

        return [
          {
            sku: '合计',
            purchaseAmt,
            cutoffAmt,
            deliveryStayAmt,
            deliveryRealAmt,
            本次交货,
            交货仓可用库存,
            库存成本,
          },
        ]
      }

      const setGlobal = (parentItem: any, item: any, key: string, astrictKey: string, i: number) => {
        parentItem.billItems.map((e: any, index: number) => {
          if (e[astrictKey] || e[astrictKey] == 0) {
            if (index >= i) {
              e[key] = item[key] > item[astrictKey] ? item[astrictKey] : item[key]
            }
          } else {
            e[key] = item[key]
          }
          return e
        })
      }

      const toCheckDay = (time: any) => {
        let date = new Date(time).valueOf() + 24 * 60 * 60 * 1000
        let newDate = new Date().valueOf()
        let timeStr = date - newDate
        if (timeStr < 0) {
          let daty = Math.abs(timeStr) / (24 * 60 * 60 * 1000)
          return {
            type: false,
            day: Math.ceil(daty),
          }
        } else {
          let daty = Math.abs(timeStr) / (24 * 60 * 60 * 1000)
          return {
            type: true,
            day: Math.ceil(daty),
          }
        }
      }

      const getWarehouseStock = async () => {
        if (!data.form.deliveryWarehouseCode) {
          return (data.form.deliveryWarehouseName = '')
        }

        let params: any = {
          inventoryItems: [],
        }
        let houseInfo = data.houseList.find((e: any) => e.warehouseCode == data.form.deliveryWarehouseCode)
        data.form.deliveryWarehouseName = houseInfo.warehouseName
        data.itemList.forEach((e: any) => {
          let obj = {
            warehouseCode: data.form.warehouseCode || '',
            marketplaceId: houseInfo.marketplaceId || '',
            sellerId: houseInfo.sellerId || '',
            sku: e?.ssku || '',
            key: e.id,
          }
          params.inventoryItems.push(obj)
        })
        const res: any = await findInventoryBatch(params)
        let resArr = res?.data?.inventoryItems || []
        data.tableList.forEach((e: any) => {
          if (e.billItems && e.billItems[0]) {
            e.billItems.forEach((el: any) => {
              let obj = resArr.find((item: any) => el.id == item.key)
              el.warehouseStock = obj.amtAvailable || obj.amtAvailable == 0 ? obj.amtAvailable : ''
              el.deliveryInventoryPrice = obj.avgPrice || obj.avgPrice == 0 ? obj.avgPrice : ''
            })
          }
        })
      }

      const getSpecName = (info: any) => {
        let item: any = info ? JSON.parse(info.productSpecs) : []
        return item.map((e: any) => e.valueCn).join(',')
      }

      return {
        ...(toRefs(data) as any),
        visible,
        open,
        handleOk,
        handleCancel,
        formRef,
        spanMethodAll,
        summary,
        setGlobal,
        toCheckDay,
        getWarehouseStock,
        getSpecName,
      }
    },
  })
</script>

<style lang="less" scoped>
  .table {
    width: 100%;

    :deep(.arco-table-td) {
      background-color: var(--color-fill-1);
    }
    :deep(.arco-table-tr-expand) {
      .arco-table-cell {
        padding: 0;
      }
      .arco-table {
        margin: 0 !important;
        .arco-table-td {
          border-bottom: 1px solid var(--color-neutral-3);
        }
      }
      background-color: #fff !important;
    }
    :deep(.child-row) {
      .arco-table-cell {
        padding: 2px 8px;
      }
    }
    :deep(.arco-table-tr-expand .arco-table-td) {
      background-color: #fff !important;
      border-bottom: none;
    }
    :deep(.arco-table-tr-expand tr:hover .arco-table-td) {
      background-color: var(--color-fill-1) !important;
    }
    :deep(.arco-table-expand .arco-table-cell) {
      display: none;
    }
    :deep(.arco-tabs-nav-tab) {
      background-color: #fff;
    }
  }

  .text-desc {
    font-size: 12px;
    margin-left: 10px;
    color: #7f7f7f;
  }

  .arco-col {
    margin-bottom: 5px;
  }

  .detail-item {
    display: flex;

    .label {
      width: 80px;
      text-align: right;
    }
    .value {
      flex: 1;
    }
  }
</style>
